package com.bootdo.program.wallpaper.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.seq.GenerateSequenceUtil;
import com.bootdo.program.wallpaper.dao.BzBaseinfoDao;
import com.bootdo.program.wallpaper.dao.TzUserDao;
import com.bootdo.program.wallpaper.dao.WalletDetailsDao;
import com.bootdo.program.wallpaper.domain.*;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;

import com.bootdo.program.wallpaper.dao.SettlemenbillDao;
import com.bootdo.program.wallpaper.service.SettlemenbillService;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(rollbackFor=Exception.class)
public class SettlemenbillService  {

	public final String PREFIX_DK="JS";

	@Autowired
	private SettlemenbillDao settlemenbillDao;

	@Autowired
	private BzBaseinfoDao bzBaseinfoDao;

	@Autowired
	private TzUserDao tzUserDao;

	@Autowired
	private WalletDetailsDao walletDetailsDao;

	@Autowired
	private WalletDetailsService walletDetailsService;

	@Autowired
	private DistributionProfitService distributionProfitService;

	public SettlemenbillDO get(Long id){
		return settlemenbillDao.get(id);
	}


	public List<SettlemenbillDO> list(Map<String, Object> map){
		return settlemenbillDao.list(map);
	}


	public int count(Map<String, Object> map){
		return settlemenbillDao.count(map);
	}


	public int save(SettlemenbillDO settlemenbill){
		return settlemenbillDao.save(settlemenbill);
	}


	@Transactional
	public int update(SettlemenbillDO settlemenbill)throws Exception{
		return settlemenbillDao.update(settlemenbill);
	}


	public int remove(Long id){
		return settlemenbillDao.remove(id);
	}


	public int batchRemove(Long[] ids){
		return settlemenbillDao.batchRemove(ids);
	}

	public int batchSave(List<SettlemenbillDO> list){
		return settlemenbillDao.batchSave(list);
	}


	public int updateStatus(int status,String startTime,String userId,Integer settlemantPlatform) throws Exception{
		Map<String,Object> map = new HashMap<>();
		map.put("status",status);
		map.put("startTime",startTime);
		map.put("userId",userId);
		map.put("settlemantPlatform",settlemantPlatform);
		return settlemenbillDao.updateStatus(map);
	}

	/**
	 * 修改日结算单
	 * @param settlemenbill
	 * @return
	 */
	public int updateSettlemenStatus(SettlemendaysBillDO settlemenbill) throws Exception{
		return settlemenbillDao.updateSettlemenStatus(settlemenbill);
	}


	public int selectCount(SettlemenbillDO settlemenbill){
		return settlemenbillDao.selectCount(settlemenbill);
	}


	/**
	 * 生成结算单
	 * @param doList 数据集合
	 * @param sTime 结算时间
	 * @param platformRate  平台抽佣百分比
	 * @param taxrate 平台税百分比
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public int addSettlemenbill(List<SettlemenbillDO> doList, String sTime, BigDecimal platformRate,
								BigDecimal taxrate,Integer settlemantPlatform) throws Exception{

		String lastDay = getLastDay();
		//添加结算单
		Date date = new Date();
		String dateStr = DateUtil.format(date, "yyyyMMddHHmmss");

		String days = DateUtil.format(date, "dd");

		int i = 0;

		//结算时间
		String time = DateUtil.format(date, "HH:mm:ss");
		DateTime settlementTime = DateUtil.parse(sTime + "-" + days + " "+time, "yyyy-MM-dd HH:mm:ss");

		for (SettlemenbillDO b : doList){
			i++;
			b.setCreateTime(date);
			b.setConfirmState(1);
			b.setStatus(1);
			b.setIncomeType(1);
			b.setTimeSlot(sTime+"-01 00:00:00 至 " + sTime+"-" +lastDay + " 23:59:59");

			b.setSettlementTime(settlementTime);
			b.setSettlementNo(PREFIX_DK + dateStr + i);
			b.setSettlemantPlatform(settlemantPlatform);
			//setScale(2,BigDecimal.ROUND_DOWN);

			//原始金额
			b.setAmount(b.getAmount().setScale(2,BigDecimal.ROUND_DOWN));
			//计算打款金额
			BigDecimal taxrateMoney = b.getAmount().multiply(taxrate);
			BigDecimal paymentAmount = b.getAmount().subtract(taxrateMoney);
			b.setPaymentAmount(paymentAmount.setScale(2,BigDecimal.ROUND_DOWN));

			//计算实际打款金额，计算平台抽取
			BigDecimal platformMoney = b.getAmount().multiply(platformRate);
			BigDecimal actualPaymentAmount = b.getAmount().subtract(taxrateMoney.add(platformMoney)).setScale(2, BigDecimal.ROUND_DOWN);;
			b.setActualPaymentAmount(actualPaymentAmount);

			b.setPlatformScale(platformRate);
			b.setPlatformRate(taxrate);

		}

		int sa = batchSave(doList);
		return sa;
	}

	public String getLastDay(){
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

		SimpleDateFormat format = new SimpleDateFormat("dd");
		String last= format.format(c.getTime());
		return last;
	}


	/**
	 * 入账用户钱包
	 * @param sTime
	 * @return
	 */
	public int addWalletInfo(String sTime,Integer settlemantPlatform) throws Exception {

		List<SettlemenbillDO> list = settlemenbillDao.selectSettlementInfo(sTime,settlemantPlatform);
		int size = list.size();
		if(size == 0){
			return -1;
		}

		List<SettlemenbillDO> doList = settlemenbillDao.selectSettlementInfoOri(sTime,settlemantPlatform);

		//修改月结算单
		int count = settlemenbillDao.updateSettlementInfo(sTime,settlemantPlatform);

		if(count > 0){
			//修改用户余额
			tzUserDao.batchUpdateBalance(list);

			for (int j = 0; j < doList.size(); j++) {
				doList.get(j).setCreateTime(new Date());
				doList.get(j).setSettlementNo(GenerateSequenceUtil.generateSequenceNo()+""+j);
				//设置为1-收入
				doList.get(j).setDtype(1);
				doList.get(j).setSettlemantPlatform(settlemantPlatform);
			}

			//新增钱包记录
			walletDetailsDao.batchSave(doList);

			//修改日结算单状态
			SettlemendaysBillDO settlemenDays = new SettlemendaysBillDO();
			settlemenDays.setUpdateUser(ShiroUtils.getUser().getUserId());
			settlemenDays.setSettlementTime(DateUtil.parse(sTime,"yyyy-MM-dd HH:mm:ss"));
			settlemenDays.setSettlemantPlatform(settlemantPlatform);
			settlemenbillDao.updateSettlemenStatusAll(settlemenDays);
			//修改广告收益
			updateStatus(3,sTime,null,settlemantPlatform);
			//修改分销收益
			distributionProfitService.updateStatus(3,sTime,null,settlemantPlatform);
		}else {
			throw new RuntimeException("入账失败");
		}
		return count;
	}

	public int updateWalletInfo(SettlemenbillDO settlemenbillDO) throws Exception {

		SettlemenbillDO aDo = settlemenbillDao.get(settlemenbillDO.getId());
		if(null == aDo){
			return -1;
		}

		TzUserDO userDO = tzUserDao.getByUserId(aDo.getUserid());
		if(null == userDO){
			return -1;
		}
		//修改月结算单
		int count = settlemenbillDao.updateSettlementInfoOne(settlemenbillDO.getId(),aDo.getSettlemantPlatform());
		if(count > 0){

			BigDecimal amount = new BigDecimal("0");
			//VIP账号，收益翻倍
			if(1 == userDO.getVipAccount()){
				amount = aDo.getAmount().multiply(new BigDecimal("2"));
			}else{
				amount = aDo.getAmount();
			}
			userDO.setBalance(null == userDO.getBalance() ? amount : userDO.getBalance().add(amount));

			//修改用户余额
			tzUserDao.updateBalance(userDO);

			//添加钱包记录
			walletDetailsService.addWallet(userDO.getUserId(),amount,aDo.getSettlemantPlatform(),1);

			//TODO 修改日结算单
			SettlemendaysBillDO settlemenDays = new SettlemendaysBillDO();
			settlemenDays.setUpdateUser(ShiroUtils.getUser().getUserId());
			settlemenDays.setSettlementTime(aDo.getSettlementTime());
			settlemenDays.setUserid(aDo.getUserid());
			settlemenDays.setDtype(aDo.getDtype());
			settlemenDays.setSettlemantPlatform(aDo.getSettlemantPlatform());
			//修改日结算单状态
			settlemenbillDao.updateSettlemenStatus(settlemenDays);

			if(1 == aDo.getDtype()){
				//修改广告收益
				updateStatus(3,DateUtil.format(aDo.getSettlementTime(),"yyyy-MM-dd HH:mm:ss"),aDo.getUserid(),
						aDo.getSettlemantPlatform());
			}else if(2 == aDo.getDtype()){
				//修改分销收益
				distributionProfitService.updateStatus(3,DateUtil.format(aDo.getSettlementTime(),"yyyy-MM-dd HH:mm:ss"),aDo.getUserid(),
						aDo.getSettlemantPlatform());
			}

		}else {
			throw new RuntimeException("入账失败");
		}
		return count;
	}

}
